<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.name" class="filter-item w-200" size="medium" placeholder="学校名称"></el-input>
            <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(true)" v-permission="'schools.index'">搜 索</el-button>
            <el-button class="filter-item" type="primary" size="medium" icon="el-icon-plus" style="float: right" @click="addSchool" v-permission="'schools.store'">新 增</el-button>
        </div>
        <el-table :data="schoolData" v-loading="loading" border style="width: 100%">
            <el-table-column width="100px" label="#" align="center">
                <template slot-scope="scope" >
                    {{query.size * (query.page-1) + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" width="250px" align="center"></el-table-column>
            <el-table-column prop="address" label="地址" width="300px" align="center"></el-table-column>
            <el-table-column prop="detail_address" label="详细地址" width="400px" align="center"></el-table-column>
            <el-table-column prop="contact_name" label="联系人" width="200px" align="center"></el-table-column>
            <el-table-column prop="contact_phone" label="联系电话" width="200px" align="center"></el-table-column>
            <el-table-column label="状态" width="150px" align="center">
                <template slot-scope="scope">
                    {{ scope.row.status === 1 ? '启用' : '停用' }}
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="添加时间" align="center"></el-table-column>
            <el-table-column prop="updated_at" label="更新时间" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button class="filter-item" icon="el-icon-edit" type="primary" size="mini" @click="editSchool(scope.row)" v-permission="'schools.update'">编 辑</el-button>
                    <el-button class="filter-item" type="primary" size="mini" @click="editSchoolRule(scope.row.rule)" v-permission="'school-rules.update'">修改规则</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog title="学校" width="700px" :visible.sync="dialogVisible">
            <el-form :model="schoolForm" :rules="rules" ref="schoolForm" label-width="120px" class="demo-schoolForm">
                <el-form-item label="学校名称" prop="name">
                    <el-input v-model="schoolForm.name"></el-input>
                </el-form-item>
                <el-form-item label="学校地址" prop="areaId" required>
                    <jw-area v-model="schoolForm.areaId" :init="initArea"></jw-area>
                </el-form-item>
                <el-form-item label="学校详细地址" prop="detail_address">
                    <el-input v-model="schoolForm.detail_address"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="contact_name">
                    <el-input v-model="schoolForm.contact_name"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contact_phone" required>
                    <el-input v-model="schoolForm.contact_phone"></el-input>
                </el-form-item>
                <el-form-item label="开发者标识" prop="dev_code">
                    <el-input v-model="schoolForm.dev_code"></el-input>
                </el-form-item>
                <el-form-item label="智慧校园ID" prop="objectid">
                    <el-input v-model="schoolForm.objectid"></el-input>
                </el-form-item>
                <el-form-item label="key" prop="key">
                    <el-input v-model="schoolForm.key"></el-input>
                </el-form-item>
                <el-form-item label="key_id" prop="key_id">
                    <el-input v-model="schoolForm.key_id"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                            v-model="schoolForm.status"
                            :active-value="1"
                            :inactive-value="0"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="submitSchoolForm" :loading="btnLoading">保存</el-button>
            </div>
        </el-dialog>
        <el-dialog title="学校规则" width="700px" :visible.sync="dialogVisible2">
            <el-form :model="schoolRuleForm" :rules="rules2" ref="schoolRuleForm" label-width="200px" class="demo-schoolRuleForm">
                <el-form-item label="早餐规则" prop="morning_rule">
                    <el-select v-model="schoolRuleForm.morning_rule" placeholder="请选择早餐规则">
                        <el-option label="手动" value="0"></el-option>
                        <el-option label="自动" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="早餐时间" prop="morning_date">
                    <el-time-picker
                            is-range
                            v-model="schoolRuleForm.morning_date"
                            range-separator="~"
                            value-format="HH:mm:ss"
                            start-placeholder="早餐开始时间"
                            end-placeholder="早餐结束时间"
                            placeholder="选择早餐时间范围">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="次日早餐截止时间" prop="morning_deadline">
                    <el-tooltip class="item" effect="dark" content="在当天预定次日早餐的截止时间" placement="right">
                        <el-time-picker
                                v-model="schoolRuleForm.morning_deadline"
                                value-format="HH:mm:ss"
                                placeholder="次日早餐截止时间">
                        </el-time-picker>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="午餐规则" prop="lunch_rule">
                    <el-select v-model="schoolRuleForm.lunch_rule" placeholder="请选择午餐规则">
                        <el-option label="手动" value="0"></el-option>
                        <el-option label="自动" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="午餐时间" prop="lunch_date" required>
                    <el-time-picker
                            is-range
                            v-model="schoolRuleForm.lunch_date"
                            range-separator="~"
                            value-format="HH:mm:ss"
                            start-placeholder="午餐开始时间"
                            end-placeholder="午餐结束时间"
                            placeholder="选择午餐时间范围">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="次日午餐截止时间" prop="lunch_deadline">
                    <el-tooltip class="item" effect="dark" content="在当天预定次日午餐的截止时间" placement="right">
                        <el-time-picker
                                v-model="schoolRuleForm.lunch_deadline"
                                value-format="HH:mm:ss"
                                placeholder="次日午餐截止时间">
                        </el-time-picker>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="晚餐规则" prop="dinner_rule">
                    <el-select v-model="schoolRuleForm.dinner_rule" placeholder="请选择晚餐规则">
                        <el-option label="手动" value="0"></el-option>
                        <el-option label="自动" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="晚餐时间" prop="dinner_date" required>
                    <el-time-picker
                            is-range
                            v-model="schoolRuleForm.dinner_date"
                            range-separator="~"
                            value-format="HH:mm:ss"
                            start-placeholder="晚餐开始时间"
                            end-placeholder="晚餐结束时间"
                            placeholder="选择晚餐时间范围">
                    </el-time-picker>
                </el-form-item>
                <el-form-item label="次日晚餐截止时间" prop="dinner_deadline">
                    <el-tooltip class="item" effect="dark" content="在当天预定次日晚餐的截止时间" placement="right">
                        <el-time-picker
                                v-model="schoolRuleForm.dinner_deadline"
                                value-format="HH:mm:ss"
                                placeholder="次日晚餐截止时间">
                        </el-time-picker>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="加餐日期限制" prop="is_limit">
                    <el-switch
                            v-model="schoolRuleForm.is_limit"
                            :active-value="1"
                            :inactive-value="0"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                    <el-tooltip class="item" effect="dark" placement="right">
                        <i class="el-icon-info" style="margin-left: 30px"></i>
                        <div slot="content">
                            若限制则只能从明天开始选择，且在加餐截止时间之前；<br/>
                            若不限制则从今天开始选择，且不考虑加餐截止时间
                        </div>
                    </el-tooltip>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2=false">取消</el-button>
                <el-button type="primary" @click="submitSchoolRuleForm">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchSchools, addSchool, editSchool, editSchoolRule } from '@/api/school'
    import { isPhoneAvailable } from '@/utils/validate'
    import JwArea from '@/components/Area'
    export default {
      name: 'school',
      data() {
        const validatePhone = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入联系电话'))
          } else {
            if (!isPhoneAvailable(value)) {
              callback(new Error('手机号码格式错误'))
            }
            callback()
          }
        }
        const validateLunch = (rule, value, callback) => {
          if (!this.schoolRuleForm.lunch_date) {
            callback(new Error('请选择午餐时间'))
          } else {
            if (this.schoolRuleForm.morning_date) {
              if (!(this.schoolRuleForm.morning_date[1] <= this.schoolRuleForm.lunch_date[0])) {
                callback(new Error('中餐和午餐时间不能有重叠'))
              }
            }
            callback()
          }
        }
        const validateDinner = (rule, value, callback) => {
          if (!this.schoolRuleForm.dinner_date) {
            callback(new Error('请选择晚餐时间'))
          } else {
            if (this.schoolRuleForm.morning_date) {
              if (!(this.schoolRuleForm.morning_date[1] <= this.schoolRuleForm.dinner_date[0])) {
                callback(new Error('中餐和晚餐时间不能有重叠'))
              }
            }
            if (this.schoolRuleForm.lunch_date) {
              if (!(this.schoolRuleForm.lunch_date[1] <= this.schoolRuleForm.dinner_date[0])) {
                callback(new Error('午餐和晚餐时间不能有重叠'))
              }
            }
            callback()
          }
        }
        return {
          btnLoading: false,
          loading: true,
          ruleOption: '',
          dialogVisible2: false,
          schoolRuleForm: {
            school_id: '',
            morning_rule: 0,
            morning_date: [],
            lunch_rule: 0,
            lunch_date: [],
            dinner_rule: 0,
            dinner_date: [],
            morning_deadline: '',
            lunch_deadline: '',
            dinner_deadline: '',
            is_limit: 0
          },
          initArea: [],
          rules2: {
            morning_rule: [
              { required: true, message: '请选择早餐规则', trigger: 'blur' }
            ],
            morning_date: [
              { required: true, message: '请选择早餐时间', trigger: 'blur' }
            ],
            lunch_rule: [
              { required: true, message: '请选择午餐规则', trigger: 'blur' }
            ],
            lunch_date: [
              { validator: validateLunch, trigger: 'blur' }
            ],
            dinner_rule: [
              { required: true, message: '请选择晚餐规则', trigger: 'blur' }
            ],
            dinner_date: [
              { validator: validateDinner, trigger: 'blur' }
            ],
            morning_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ],
            lunch_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ],
            dinner_deadline: [
              { required: true, message: '请选择截止时间', trigger: 'blur' }
            ]
          },
          rules: {
            name: [
              { required: true, message: '请输入学校名称', trigger: 'blur' },
              { min: 2, max: 20, message: '输入的学校名称长度在2 ~ 20个字符之间' }
            ],
            areaId: [
              { required: true, message: '请选择所属省市区', trigger: 'blur' }
            ],
            detail_address: [
              { required: true, message: '请输入详细地址', trigger: 'blur' }
            ],
            contact_name: [
              { required: true, message: '请输入联系人名称', trigger: 'blur' },
              { min: 2, max: 20, message: '输入的联系人名称长度在2 ~ 20个字符之间' }
            ],
            contact_phone: [
              { validator: validatePhone, trigger: 'blur' }
            ]
          },
          provinces: [],
          cities: [],
          areas: [],
          option: '',
          schoolForm: {
            areaId: '',
            id: '',
            name: '',
            detail_address: '',
            contact_name: '',
            contact_phone: '',
            dev_code: '',
            objectid: '',
            key: '',
            key_id: '',
            status: 1
          },
          dialogVisible: false,
          schoolData: [],
          total: 0,
          query: {
            name: '',
            size: 10,
            page: 1,
            addressId: ''
          }
        }
      },
      components: {
        JwArea: JwArea
      },
      methods: {
        submitSchoolRuleForm() {
          this.$refs['schoolRuleForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              editSchoolRule(this.schoolRuleForm, this.schoolRuleForm.id).then(res => {
                if (res.result === 'failed') {
                  this.$message.error(res.msg)
                } else {
                  this.$message.success('保存成功')
                  this.dialogVisible2 = false
                  this.fetchList()
                }
              }).catch(err => {
                this.$handleNotFound(err, '学校规则不存在')
              })
            }
          })
        },
        editSchoolRule(row) {
          if (this.$refs['schoolRuleForm'] !== undefined) {
            this.$refs['schoolRuleForm'].clearValidate()
          }
          Object.assign(this.schoolRuleForm, row)
          this.schoolRuleForm.morning_rule = row.morning_rule.toString()
          this.schoolRuleForm.lunch_rule = row.lunch_rule.toString()
          this.schoolRuleForm.dinner_rule = row.dinner_rule.toString()
          this.schoolRuleForm.morning_date = [row.morning_start, row.morning_end]
          this.schoolRuleForm.lunch_date = [row.lunch_start, row.lunch_end]
          this.schoolRuleForm.dinner_date = [row.dinner_start, row.dinner_end]
          this.dialogVisible2 = true
        },
        handleSizeChange(size) {
          this.query.size = size
          this.fetchList()
        },
        handleCurrentChange(page) {
          this.query.page = page
          this.fetchList()
        },
        // 获取学校信息列表
        fetchList(resetPage = false) {
          this.loading = true
          if (resetPage === true) {
            this.query.page = 1
          }
          fetchSchools(this.query).then(res => {
            this.schoolData = res.data
            this.total = res.meta.total
            this.loading = false
          })
        },
        // 重置表单验证
        resetForm(formName) {
          // 第一次新增数据时为空对象undefined
          if (this.$refs[formName] !== undefined) {
            this.$refs[formName].resetFields()
          }
        },
        // 添加学校信息
        addSchool() {
          this.resetForm('schoolForm')
          this.initArea = []
          this.schoolForm = {}
          this.schoolForm.areaId = []
          this.dialogVisible = true
          this.option = 'add'
          Object.assign(this.schoolForm, this.$options.data().schoolForm)
        },
        // 编辑学校信息
        editSchool(row) {
          this.initArea = [
            parseInt(row.province),
            parseInt(row.city),
            parseInt(row.country)
          ]
          this.schoolForm.areaId = this.initArea
          this.dialogVisible = true
          this.option = 'edit'
          Object.existAssign(this.schoolForm, row)
        },
        // 提交学校表单
        submitSchoolForm() {
          this.btnLoading = true
          this.$refs['schoolForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              if (this.option === 'add') {
                addSchool(this.schoolForm).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('添加成功')
                    this.fetchList()
                    this.dialogVisible = false
                    this.btnLoading = false
                  }
                }).catch(err => {
                  this.$handleNotFound(err)
                  this.btnLoading = false
                })
              }
              if (this.option === 'edit') {
                editSchool(this.schoolForm, this.schoolForm.id).then(res => {
                  this.$message.success('编辑成功')
                  this.fetchList()
                  this.dialogVisible = false
                  this.btnLoading = false
                }).catch(err => {
                  this.$handleNotFound(err, '学校不存在')
                  this.btnLoading = false
                })
              }
            } else {
              this.btnLoading = false
            }
          })
        }
      },
      created() {
        this.fetchList()
      }
    }
</script>

<style scoped>

</style>
